/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Host.java
 *
 * Created on 21/10/2011, 10:42:26
 */
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import util.PersonalizarJFrame;

/**
 *
 * @author Cleiton
 */
public class InterfaceHost extends javax.swing.JFrame {

    private PersonalizarJFrame personalizarJFrame;
    private PersonalizarTable personalizarTable;
    /**
     * Cria um objeto host para passar informações.
     */
    private HostImpl hostImpl;

    /**
     * Enviar pacote de um host para um roteador.
     */
    //TODO Fazer 
    public void enviarPacote() {
    }

    /** Creates new form Host */
    public InterfaceHost() {
        try {
            hostImpl = new HostImpl() {

                @Override
                public void atualizarTabela(Pacote pacote) {
                 //   String algoritmo = (pacote.getAlgoritmo() == 0) ? "Dijkstra" : "Bell";
                    DefaultTableModel defaultTableModel = personalizarTable.getDefaultTableModel();
                    Integer passos = pacote.getTTL_maximo() - pacote.getTTL();
                    defaultTableModel.addRow(new Object[]{pacote.getNameOrigem(), pacote.extrairDados(), passos});
                }
            };

        } catch (RemoteException ex) {
            Logger.getLogger(InterfaceHost.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Conectando ao servidor");
        hostImpl.conectarServidor();
        System.out.println("Esperando Servidor Inserir nome");
        hostImpl.servidorCentarlAlteraNomeHost();
        System.out.println("Criando Host Como Servidor");
        instanciarHostComoServidor();
        personalizarJFrame = new PersonalizarJFrame(this);
        personalizarJFrame.setLookFeel();
        initComponents();
        this.setTitle("Host " + hostImpl.getNome());
        personalizarJFrame.setPositionRElative();
        instanciarPersonalizarTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jepMensagem = new javax.swing.JEditorPane();
        jLabel3 = new javax.swing.JLabel();
        jtfTtl = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jtfDesstino = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jtfIdPacote = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbPacotes = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jepMensagemRecebidas = new javax.swing.JEditorPane();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Host");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        jLabel1.setForeground(new java.awt.Color(0, 204, 0));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Enviar Pacote");

        jLabel2.setText("Mensagem:");

        jScrollPane1.setViewportView(jepMensagem);

        jLabel3.setText("TTL:");

        jtfTtl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfTtlActionPerformed(evt);
            }
        });

        jLabel4.setText("Host de Destino:");

        jtfDesstino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDesstinoActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/download.png"))); // NOI18N
        jButton1.setText("Enviar Pacote");
        jButton1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jButton1StateChanged(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel7.setText("Id pacote:");

        jtfIdPacote.setEditable(false);
        jtfIdPacote.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtfIdPacote.setText("1");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(168, 168, 168)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
                .addGap(198, 198, 198))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(jLabel3)
                .addGap(29, 29, 29)
                .addComponent(jtfTtl, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfDesstino, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfIdPacote, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 522, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(23, 23, 23))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfTtl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jtfDesstino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jtfIdPacote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addGap(18, 18, 18))
        );

        jLabel5.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        jLabel5.setForeground(new java.awt.Color(0, 204, 0));
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Pacotes Recebidos");

        jtbPacotes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Host", "Mensagem", "Nº de  Nós Percorridos"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtbPacotes);

        jLabel6.setText("Mensagem:");

        jepMensagemRecebidas.setEditable(false);
        jScrollPane3.setViewportView(jepMensagemRecebidas);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(82, 82, 82)
                .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                .addGap(100, 100, 100))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 619, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE))
                .addContainerGap())
        );

        jSeparator1.setForeground(new java.awt.Color(255, 51, 51));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtfTtlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfTtlActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtfTtlActionPerformed

    private void jtfDesstinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDesstinoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtfDesstinoActionPerformed
    /**
     * Envia um pacote para o Gateway.
     * @param evt 
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Pacote pacote = getPacote();
        if (jtfDesstino.getText().toLowerCase().equals("localhost")) {
            try {
                hostImpl.receberMensagem(pacote);

            } catch (RemoteException ex) {
                Logger.getLogger(InterfaceHost.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            hostImpl.enviaInformaçaoServidor();
            Roteador roteador = hostImpl.getRoteador();
            try {
                
                roteador.receberMensagem(pacote);
            } catch (RemoteException ex) {
                Logger.getLogger(InterfaceHost.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        Integer id = pacote.getId() + 1;
        jtfIdPacote.setText(id.toString());
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jButton1StateChanged
    }//GEN-LAST:event_jButton1StateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InterfaceHost().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JEditorPane jepMensagem;
    private javax.swing.JEditorPane jepMensagemRecebidas;
    private javax.swing.JTable jtbPacotes;
    private javax.swing.JTextField jtfDesstino;
    private javax.swing.JTextField jtfIdPacote;
    private javax.swing.JTextField jtfTtl;
    // End of variables declaration//GEN-END:variables

    /**
     * Inicializa o Servidor do Host para receber informações.
     */
    private void instanciarHostComoServidor() {
        try {
            System.out.println("rmi://" + hostImpl.getIp() + "/" + hostImpl.getNome());
            Naming.rebind("rmi://" + hostImpl.getIp() + "/" + hostImpl.getNome(), hostImpl);
        } catch (RemoteException ex) {
            Logger.getLogger(InterfaceHost.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(InterfaceHost.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void instanciarPersonalizarTable() {
        personalizarTable = new PersonalizarTable(jtbPacotes) {

            @Override
            void actionClicarTable(int linha) {
                actionLinhaAlterada(linha);
            }

            @Override
            void actionLinhaAlterada(int linha) {
                String mensagem;
                try {
                    mensagem = getDefaultTableModel().getValueAt(linha, 1).toString();
                } catch (NullPointerException e) {
                    mensagem = "nova";
                }
                jepMensagemRecebidas.setText(mensagem);
            }
        };
    }

    private Pacote getPacote() {
        String nameDestino = jtfDesstino.getText();
        String dados = jepMensagem.getText();
        int ttl = Integer.parseInt(jtfTtl.getText());
        Pacote pacote = new Pacote(hostImpl.getNome(), nameDestino, ttl, dados, hostImpl.getPacotesEnviados());
        return pacote;
    }
}
